<template>
  <p-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="标签模板编号" :labelCol = "{span: 4}">
              <p-input
                placeholder="标签模板编号"
                v-model="queryParam.labelTemplateNo"
              ></p-input>
            </p-form-item>
          </p-col>
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <p-button type="primary" @click="searchQuery" icon="search">查询</p-button>
              <p-button
                type="primary"
                @click="searchReset"
                icon="reload"
                style="margin-left: 8px"
              >重置</p-button>
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button v-if="mainId" @click="handleAdd" type="primary" icon="plus">新增</p-button>

      <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
        <p-button
          v-if=" item.optType=='js' "
          :key=" 'cgbtn'+index "
          @click="cgButtonJsHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
        <p-button
          v-else-if=" item.optType=='action' "
          :key=" 'cgbtn'+index "
          @click="cgButtonActionHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
      </template>

      <p-dropdown v-if="selectedRowKeys.length > 0">
        <p-menu slot="overlay">
          <p-menu-item key="1" @click="batchDel">
            <p-icon type="delete" />删除
          </p-menu-item>
        </p-menu>
        <p-button style="margin-left: 8px">
          批量操作
          <p-icon type="down" />
        </p-button>
      </p-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <!-- <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="tableScroll"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
      > -->

      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{fixed:true,selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
      >      
        <template slot="status" slot-scope="text, record">
          <f-switch v-model="record.status" field="record" dictCode="mes_open_close" size="small" />
        </template>

        <template slot="labelTemplateName" slot-scope="text, record">
          <a :href="record.ureportAddress" target="_blank">{{text}}</a>
        </template>        

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        
        <template slot="labelTemplateLength" slot-scope="text">
          {{ labelTemplateLengthKeys[text]}}
        </template>        

        <template slot="labelType" slot-scope="text">
          {{ labelTypeKeys[text]}}
        </template>

        <template slot="labelColor" slot-scope="text">
          {{ labelColorKeys[text]}}
        </template>

        <template slot="labelColor" slot-scope="text">
          {{ labelColorKeys[text]}}
        </template>

        <template slot="ribbonsType" slot-scope="text">
          {{ ribbonsTypeKeys[text]}}
        </template>

        <template slot="printerType" slot-scope="text">
          {{ printerTypeKeys[text]}}
        </template>

        <template slot="containSn" slot-scope="text">
          {{ containSnKeys[text]}}
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <p-divider type="vertical" />
          <p-dropdown>
            <a class="ant-dropdown-link">
              更多
              <p-icon type="down" />
            </a>
            <p-menu slot="overlay">
              <p-menu-item>
                <p-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </p-popconfirm>
              </p-menu-item>
              <template
                v-if="cgButtonLinkList && cgButtonLinkList.length>0"
                v-for="(btnItem,btnIndex) in cgButtonLinkList"
              >
                <p-menu-item :key=" 'cgbtnLink'+btnIndex " v-if="showLinkButton(btnItem,record)">
                  <a
                    href="javascript:void(0);"
                    @click="cgButtonLinkHandler(record,btnItem.buttonCode,btnItem.optType)"
                  >
                    <p-icon v-if="btnItem.buttonIcon" :type="btnItem.buttonIcon" />
                    {{ btnItem.buttonName }}
                  </a>
                </p-menu-item>
              </template>
            </p-menu>
          </p-dropdown>
        </span>

      </p-table>
    </div>

    <mesBcProductList-modal
      ref="modalForm"
      :EnhanceJS="EnhanceJS"
      @ok="modalFormOk"
      :mainId="mainId"
    ></mesBcProductList-modal>
  </p-card>
</template>

<script>
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import MesBcProductListModal from "./MesBcProductListModal";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction } from "@/api/manage";
import { ajaxGetDictItems } from '@/api/api'
import { timestampToDatetime } from "@/utils/util";

export default {
  name: "MesBcProductListList",
  mixins: [JeecgListMixin],
  components: { MesBcProductListModal },
  props: {
    mainId: {
      type: String,
      default: "",
      required: false,
    },
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList();
        } else {
          this.queryParam["mesProductLabelId"] = val;
          this.loadData(1);
        }
      },
    },
  },
  data() {
    return {
      labelTemplateLengthKeys: {},
      labelTypeKeys: {},
      labelColorKeys: {},
      ribbonsTypeKeys: {},
      printerTypeKeys: {},
      containSnKeys: {},

      description: "产品标签维护管理页面",
      disableMixinCreated: true,
      EnhanceJS: "",
      cgButtonLinkList: [],
      cgButtonList: [],
      code: "",
      // 表头
      columns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "标签模板编号",
          align: "center",
          dataIndex: "labelTemplateNo",
        },
        {
          title: "标签模板名称",
          align: "center",
          dataIndex: "labelTemplateName",
          scopedSlots: { customRender: "labelTemplateName" }
        },
        {
          title: "标签模板描述",
          align: "center",
          dataIndex: "labelTemplateDescrtion",
        },
        {
          title: "标签模板尺寸",
          align: "center",
          dataIndex: "labelTemplateLength",
          scopedSlots: { customRender: "labelTemplateLength" },
        },
        {
          title: "标签类型",
          align: "center",
          dataIndex: "labelType",
          scopedSlots: { customRender: "labelType" },
        },          
        {
          title: "责任部门",
          align: "center",
          dataIndex: "dptname",
        },
        {
          title: "标签纸颜色",
          align: "center",
          dataIndex: "labelColor",
          scopedSlots: { customRender: "labelColor" },
        },
        {
          title: "碳带型号",
          align: "center",
          dataIndex: "ribbonsType",
          scopedSlots: { customRender: "ribbonsType" },
        },
        {
          title: "打印机型号",
          align: "center",
          dataIndex: "printerType",
          scopedSlots: { customRender: "printerType" },
        },
        {
          title: "是否包含流水号",
          align: "center",
          dataIndex: "containSn",
          scopedSlots: { customRender: "containSn" },
        },
        {
          title: "状态",
          align: "center",
          dataIndex: "status",
          scopedSlots: { customRender: "status" },
        },
        {
          title: "创建人 ",
          align: "center",
          dataIndex: "createBy",
        },
        {
          title: "创建日期 ",
          align: "center",
          dataIndex: "createTime",
          customRender: function (text) {
            return timestampToDatetime(text);
            // return !text?"":(text.length>10?text.substr(0,10):text)
          },
        },
        {
          title: "备注",
          align: "center",
          dataIndex: "remark",
        },
        {
          title: "打印份数",
          align: "center",
          dataIndex: "prtintQty",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          width: 110,
          fixed: "right",
          scopedSlots: { customRender: "action" },
        },

      ],
      url: {
        list: "/mes-code/mesBcProductList/list",
        delete: "/mes-code/mesBcProductList",
        deleteBatch: "/mes-code/mesBcProductLabel/deleteBatchMesBcProductList",
        getColumns: "/mes-code/online/cgform/api/getColumns/",
        buttonAction: "/mes-code/online/cgform/api/doButton",
      },
      dictOptions: {},
    };
  },

  computed: {
    tableScroll: function () {
      if (this.columns.length > 12) {
        return { x: this.columns.length * 160 + 40 };
      }
    },
  },

  created() {
    this.setdefColumns();
    this.initButtonList();
    this.getObjKeys();
  },
  methods: {

    getObjKeys(){
      [
        {dictCode: 'mes-label-template-length', keysName: 'labelTemplateLengthKeys'},
        {dictCode: 'mes_label_type', keysName: 'labelTypeKeys'},
        {dictCode: 'mes_label_color', keysName: 'labelColorKeys'},
        {dictCode: 'mes-ribbons-type', keysName: 'ribbonsTypeKeys'},
        {dictCode: 'mes_printer_type', keysName: 'printerTypeKeys'},
        {dictCode: 'ba_yn', keysName: 'containSnKeys'},
      ].forEach( ({dictCode, keysName}) => {
        ajaxGetDictItems(dictCode).then( res => {
          const obj = {}
          if(res.success) {
            res.data.forEach( ele => {
              obj[ele.value] = ele.text
            } )  
          }
          this[keysName] = obj
        } )
      } )

    },

    handleAdd() {
      this.$refs.modalForm.showModal();
    },

    handleEdit(record){
      this.$refs.modalForm.showModal(record);
    },

    handleDelete(id) {
      deleteAction(this.url.delete + "/" + id).then((res) => {
        if (res.success) {
          this.$message.info("删除成功");
          this.loadData(1);
        }
      });
    },

    loadData(arg) {
      if (!this.url || !this.url.list) {
        console.log("请设置url.list属性!");
        return;
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams(); // 查询条件
      params.mesProductLabelId = this.mainId;
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records;
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.$nextTick( () => {
          this.loading = false;
        } )  
      });
    },

    setdefColumns() {
      if (this.columns.length > 12) {
        let arrLength = this.columns.length - 1;
        this.columns[arrLength]["fixed"] = "right";
        this.columns[arrLength]["width"] = 200;
        this.columns[0]["width"] = 70;
        this.columns[0]["fixed"] = "left";
      }
    },

    clearList() {
      this.dataSource = [];
      this.selectedRowKeys = [];
      this.ipagination.current = 1;
    },
    //2020/7/9
    initDictConfig() {},
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },
    initButtonList() {
      getAction(`${this.url.getColumns}8ac49ec7733bce48017345dfb77a0076`).then(
        (res) => {
          console.log("--获取自定义按钮->>", res);
          if (res.success) {
            this.code = res.data.code;
            this.initCgButtonList(res.data.cgButtonList);
            this.initCgEnhanceJs(res.data.enhanceJs);
          } else {
            this.$message.warning(res.msg);
          }
        }
      );
    },
    initCgEnhanceJs(enhanceJs) {
      //console.log("--onlineList-js增强",enhanceJs)
      if (enhanceJs) {
        let Obj = eval("(" + enhanceJs + ")");
        this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
        this.cgButtonJsHandler("created");
      } else {
        this.EnhanceJS = "";
      }
    },
    initCgButtonList(btnList) {
      let linkArr = [];
      let buttonArr = [];
      if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
          let temp = btnList[i];
          if (temp.buttonStyle == "button") {
            buttonArr.push(temp);
          } else if (temp.buttonStyle == "link") {
            linkArr.push(temp);
          }
        }
      }
      this.cgButtonLinkList = [...linkArr];
      this.cgButtonList = [...buttonArr];
      console.log("链接增强", this.cgButtonLinkList);
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },
    cgButtonActionHandler(buttonCode) {
      //处理自定义button的 需要配置该button自定义sql
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      }
      let params = {
        formId: this.code,
        buttonCode: buttonCode,
        dataId: this.selectedRowKeys[0],
      };
      console.log("自定义按钮请求后台参数：", params);
      postAction(this.url.buttonAction, params).then((res) => {
        if (res.success) {
          this.loadData();
          this.$message.success("处理完成!");
        } else {
          this.$message.warning("处理失败!");
        }
      });
    },
    cgButtonLinkHandler(record, buttonCode, optType) {
      if (optType == "js") {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this, record);
        }
      } else if (optType == "action") {
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: record.id,
        };
        console.log("自定义按钮link请求后台参数：", params);
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      }
    },
  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
</style>
